package com.hdoit.ares.logical.insu.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.brokerage.service.ICarBrokerageRecordService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.cust.service.ISendMsgService;
import com.hdoit.ares.logical.insu.dao.IFanhuaCarDao;
import com.hdoit.ares.logical.insu.model.FanhuaCar;
import com.hdoit.ares.logical.insu.model.FanhuaCarBusinessRiskKinds;
import com.hdoit.ares.logical.insu.service.IFanhuaCarBusinessRiskKindsService;
import com.hdoit.ares.logical.insu.service.IFanhuaCarService;
import com.hdoit.ares.logical.policy.service.IListPolicyService;
import com.hdoit.ares.logical.tp.zzb.model.ZzbDataCallback;
import com.hdoit.ares.logical.tp.zzb.service.IInsbregionService;
import com.hdoit.ares.logical.tp.zzb.service.IPrvnameService;
import com.hdoit.ares.logical.tp.zzb.service.ITomeasureService;
import com.hdoit.ares.logical.viewmodel.insu.FanhuaCarSearch;
import com.hdoit.ares.selfcommon.utils.SsmConfiguration;
import com.hdoit.ares.selfcommon.utils.SsmManageContainer;
import com.tennetcn.common.dao.base.impl.SuperService;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.logical.systask.service.ISmsSendService;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.log.dialect.log4j2.Log4j2LogFactory;

/**
 * @author caochengmeng
 * @email
 * @createtime 2017年12月20日 17:27:14
 * @comment
 */
@Component
public class FanhuaCarServiceImpl extends SuperService<FanhuaCar> implements IFanhuaCarService {

	private IWithdrawParamService withdrawParamService;
	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}
	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}

	private ITomeasureService tomeasureService;
	public ITomeasureService getTomeasureService() {
		return tomeasureService;
	}
	@Resource
	public void setTomeasureService(ITomeasureService tomeasureService) {
		this.tomeasureService = tomeasureService;
	}

	private IPrvnameService prvnameService;	
	public IPrvnameService getPrvnameService() {
		return prvnameService;
	}
	@Resource
	public void setPrvnameService(IPrvnameService prvnameService) {
		this.prvnameService = prvnameService;
	}
	
	private IInsbregionService insbregionService;
	public IInsbregionService getInsbregionService() {
		return insbregionService;
	}
	@Resource
	public void setInsbregionService(IInsbregionService insbregionService) {
		this.insbregionService = insbregionService;
	}

	private ICustomerService customerService;	
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	private ISmsSendService smsSendService;
	public ISmsSendService getSmsSendService() {
		return smsSendService;
	}
	@Resource
	public void setSmsSendService(ISmsSendService smsSendService) {
		this.smsSendService = smsSendService;
	}

	private IFanhuaCarDao fanhuaCarDao;
	public IFanhuaCarDao getFanhuaCarDao() {
		return fanhuaCarDao;
	}
	@Resource
	public void setFanhuaCarDao(IFanhuaCarDao fanhuaCarDao) {
		this.fanhuaCarDao = fanhuaCarDao;
	}
	
	private IFanhuaCarBusinessRiskKindsService fanhuaCarBusinessRiskKindsService;


	public IFanhuaCarBusinessRiskKindsService getFanhuaCarBusinessRiskKindsService() {
		return fanhuaCarBusinessRiskKindsService;
	}
	@Resource
	public void setFanhuaCarBusinessRiskKindsService(IFanhuaCarBusinessRiskKindsService fanhuaCarBusinessRiskKindsService) {
		this.fanhuaCarBusinessRiskKindsService = fanhuaCarBusinessRiskKindsService;
	}

	private ICarBrokerageRecordService carBrokerageRecordService;
	public ICarBrokerageRecordService getCarBrokerageRecordService() {
		return carBrokerageRecordService;
	}
	@Resource
	public void setCarBrokerageRecordService(ICarBrokerageRecordService carBrokerageRecordService) {
		this.carBrokerageRecordService = carBrokerageRecordService;
	}
	
	private IListPolicyService listPolicyService;
	public IListPolicyService getListPolicyService() {
		return listPolicyService;
	}
	@Resource
	public void setListPolicyService(IListPolicyService listPolicyService) {
		this.listPolicyService = listPolicyService;
	}
	
	private ISendMsgService sendMsgService;
	public ISendMsgService getSendMsgService() {
		return sendMsgService;
	}
	@Resource
	public void setSendMsgService(ISendMsgService sendMsgService) {
		this.sendMsgService = sendMsgService;
	}
	
	@Override
	public List<FanhuaCar> queryAllCarInsurance(String customerId) {
		return fanhuaCarDao.queryAllCarInsurance(customerId);
	}

	@Override
	public FanhuaCar queryCarInsuDetail(String orderId) {
		return fanhuaCarDao.queryCarInsuDetail(orderId);
	}

	@Override
	public FanhuaCar queryCarInsuDetailBytaskId(String taskId, String taskState) {
		return fanhuaCarDao.queryCarInsuDetailBytaskId(taskId, taskState);
	}
	
	@Override
	public FanhuaCar queryFanhuaCar(String oid){
		return fanhuaCarDao.queryFanhuaCar(oid);
	}

	@Override
	public List<FanhuaCar> queryAllCarInsu(String customerId) {
		return fanhuaCarDao.queryAllCarInsu(customerId);
	}

	@Override
	public List<FanhuaCar> queryAreadyCarInsu(String customerId) {
		return fanhuaCarDao.queryAreadyCarInsu(customerId);
	}

	@Override
	public List<FanhuaCar> queryYesCarInsu(String customerId) {
		return fanhuaCarDao.queryYesCarInsu(customerId);
	}

	@Override
	public List<FanhuaCar> queryNoCarInsu(String customerId) {
		return fanhuaCarDao.queryNoCarInsu(customerId);
	}

	@Override
	public List<FanhuaCar> queryList(FanhuaCarSearch fanhuaCarSearch, PagerModel pagerModel) {

		return fanhuaCarDao.queryList(fanhuaCarSearch, pagerModel);
	}

	// 车险综合解析
	@Override
	public String fanhuaCarCallback(ZzbDataCallback zzbDataCallback) throws RuntimeException {
		FanhuaCar fanhuaCar = new FanhuaCar();
		if ("00".equals(zzbDataCallback.getRespCode())) {
			fanhuaCar.setId(CommonUtils.getKeyId());// 车险订单表添加主键
			fanhuaCar.setTaskId(zzbDataCallback.getTaskId());
			fanhuaCar.setCreateDate(zzbDataCallback.getRequestDate());
			fanhuaCar.setCustomerId(zzbDataCallback.getChannelUserId());
			fanhuaCar.setPrvName(zzbDataCallback.getPrvName());
			fanhuaCar.setTaskState(zzbDataCallback.getTaskState());
			fanhuaCar.setErrorMsg(zzbDataCallback.getErrorMsg());
			// 车辆详情
			String carInfoJsonStr = zzbDataCallback.getCarInfo();
			Map<String, Object> carInfoMap = JSONUtil.parseObj(carInfoJsonStr);
			if (!StringUtils.isEmpty(carInfoMap)) {
				fanhuaCar.setVehicleName(MapUtils.getString(carInfoMap, "vehicleName"));
				fanhuaCar.setCarLicenseNo(MapUtils.getString(carInfoMap, "carLicenseNo"));
				fanhuaCar.setCarProperty(MapUtils.getString(carInfoMap, "carProperty"));
			}
			
			// 车主详情
			String carOwnerJsonStr = zzbDataCallback.getCarOwner();
			Map<String, Object> carOwnerMap = JSONUtil.parseObj(carOwnerJsonStr);
			if (!StringUtils.isEmpty(carOwnerMap)) {
				fanhuaCar.setCarOwnerName(MapUtils.getString(carOwnerMap, "name"));
				fanhuaCar.setCarOwnerPhone(MapUtils.getString(carOwnerMap, "phone"));
			}

			// 保险配置
			String insureInfoJsonStr = zzbDataCallback.getInsureInfo();
			Map<String, Object> insureInfoMap = JSONUtil.parseObj(insureInfoJsonStr);
			if (!StringUtils.isEmpty(insureInfoMap)) {
				// 交强险
				String efcInsureInfoJsonStr = MapUtils.getString(insureInfoMap, "efcInsureInfo");
				if (!StringUtils.isEmpty(efcInsureInfoJsonStr)) 
				{
					Map<String, Object> efcInsureInfoMap = JSONUtil.parseObj(efcInsureInfoJsonStr);
					fanhuaCar.setEfcInsureInfoAmount(MapUtils.getString(efcInsureInfoMap, "amount"));
					fanhuaCar.setEfcInsureInfoPremium(MapUtils.getString(efcInsureInfoMap, "premium"));
					fanhuaCar.setEfcInsureInfoDiscountRate(MapUtils.getString(efcInsureInfoMap, "discountRate"));

					String policyNo = MapUtils.getString(efcInsureInfoMap, "policyNo");
					if (!StringUtils.isEmpty(policyNo)) {
						fanhuaCar.setEfcInsureInfoPolicyNo(policyNo);
					}

					try {
						String startDate = MapUtils.getString(efcInsureInfoMap, "startDate");
						if (!StringUtils.isEmpty(startDate)) {
							fanhuaCar.setEfcInsureInfoStartDate(DateUtils.parseDate(startDate));
						}
						String endDate = MapUtils.getString(efcInsureInfoMap, "endDate");
						if (!StringUtils.isEmpty(endDate)) {
							fanhuaCar.setEfcInsureInfoEndDate(DateUtils.parseDate(endDate));
						}
					} catch (Exception e) {
						Log4j2LogFactory.get().error("EfcInsureInfoDate save time error");
					}
				}else{
					Log4j2LogFactory.get().error("efcInsureInfoMap save error"); 
				}
				
				// 车船税
				String taxInsureInfoJsonStr = MapUtils.getString(insureInfoMap, "taxInsureInfo");
				if (!StringUtils.isEmpty(taxInsureInfoJsonStr)) {
					Map<String, Object> taxInsureInfoMap = JSONUtil.parseObj(taxInsureInfoJsonStr);
					String taxFee = MapUtils.getString(taxInsureInfoMap, "taxFee");
					if (!StringUtils.isEmpty(taxFee)) {
						fanhuaCar.setTaxInsureInfoTaxFee(taxFee);
					}
					String lateFee = MapUtils.getString(taxInsureInfoMap, "lateFee");
					if (!StringUtils.isEmpty(lateFee)) {
						fanhuaCar.setTaxInsureInfoLateFee(lateFee);
					}
				}else{
					Log4j2LogFactory.get().error("taxInsureInfoJsonStr save error");; 
				}

				// 商业险
				String bizInsureInfoJsonStr = MapUtils.getString(insureInfoMap, "bizInsureInfo");
				Map<String, Object> bizInsureInfoMap = JSONUtil.parseObj(bizInsureInfoJsonStr);
				if (!StringUtils.isEmpty(bizInsureInfoMap)) {
					fanhuaCar.setBizInsureInfoPremium(MapUtils.getString(bizInsureInfoMap, "premium"));
					fanhuaCar.setBizInsureInfoDiscountRate(MapUtils.getString(bizInsureInfoMap, "discountRate"));
					fanhuaCar.setBizInsureInfoNfcPremium(MapUtils.getString(bizInsureInfoMap, "nfcPremium"));
					// 承保成功才有商业险保单号
					String policyNo = MapUtils.getString(bizInsureInfoMap, "policyNo");
					if (!StringUtils.isEmpty(policyNo)) {
						fanhuaCar.setBizInsureInfoPolicyNo(policyNo);
					}

					fanhuaCar.setRiskKinds(MapUtils.getString(bizInsureInfoMap, "riskKinds"));
					try {
						String startDate = MapUtils.getString(bizInsureInfoMap, "startDate");
						if (!StringUtils.isEmpty(startDate)) {
							fanhuaCar.setBizInsureInfoStartDate(DateUtils.parseDate(startDate));
						}
						String endDate = MapUtils.getString(bizInsureInfoMap, "endDate");
						if (!StringUtils.isEmpty(endDate)) {
							fanhuaCar.setBizInsureInfoEndDate(DateUtils.parseDate(endDate));
						}
					} catch (Exception e) {
						Log4j2LogFactory.get().error("bizInsureInfoDate save error"); 
					}
				}
				String totalPremium = MapUtils.getString(insureInfoMap, "totalPremium");
				if (!StringUtils.isEmpty(totalPremium)) {
					fanhuaCar.setTotalPremium(MapUtils.getString(insureInfoMap, "totalPremium"));
				}
			}

			// 投保人
			String applicantJsonStr = zzbDataCallback.getApplicant();
			Map<String, Object> applicantMap = JSONUtil.parseObj(applicantJsonStr);
			if (!StringUtils.isEmpty(applicantMap)) {
				fanhuaCar.setApplicantName(MapUtils.getString(applicantMap, "name"));
				fanhuaCar.setApplicantIdcardNo(MapUtils.getString(applicantMap, "idcardNo"));
				fanhuaCar.setApplicantGender(MapUtils.getString(applicantMap, "gender"));
				fanhuaCar.setApplicantIdcardType(MapUtils.getString(applicantMap, "idcardType"));
				fanhuaCar.setApplicantEmail(MapUtils.getString(applicantMap, "email"));
				fanhuaCar.setApplicantMobile(MapUtils.getString(applicantMap, "mobile"));
			}

			// 被保人
			String insuredJsonStr = zzbDataCallback.getInsured();
			Map<String, Object> insuredMap = JSONUtil.parseObj(insuredJsonStr);
			if (!StringUtils.isEmpty(insuredMap)) {
				fanhuaCar.setInsuredName(MapUtils.getString(insuredMap, "name"));
				fanhuaCar.setInsuredIdcardNo(MapUtils.getString(insuredMap, "idcardNo"));
				fanhuaCar.setInsuredGender(MapUtils.getString(insuredMap, "gender"));
				fanhuaCar.setInsuredIdcardType(MapUtils.getString(insuredMap, "idcardType"));
				fanhuaCar.setInsuredEmail(MapUtils.getString(insuredMap, "email"));
				fanhuaCar.setInsuredMobile(MapUtils.getString(insuredMap, "mobile"));
			}

			// 影像资料
			String imageInfo = zzbDataCallback.getImageInfos();
			if (!StringUtils.isEmpty(imageInfo)) {
				fanhuaCar.setImageInfos(imageInfo);
			}else{
				Log4j2LogFactory.get().error("imageInfo save error"); 
			}

			// 报价有效期/支付有效期
			try {
				String quoteValidTime = DateUtils.convertDate2String("yy-MM-dd HH:mm:ss", zzbDataCallback.getQuoteValidTime());
				if (!StringUtils.isEmpty(quoteValidTime)) {
					fanhuaCar.setQuoteValidTime(DateUtils.parseDateTime(quoteValidTime));
				}
				String payValidTime = DateUtils.convertDate2String("yy-MM-dd HH:mm:ss", zzbDataCallback.getQuoteValidTime());
				if (!StringUtils.isEmpty(payValidTime)) {
					fanhuaCar.setPayValidTime(DateUtils.parseDateTime(payValidTime));
				}
			} catch (Exception e) {
				System.err.println(e);
			}

			// 快递
			try {
				String deliveryJsonStr = zzbDataCallback.getDelivery();
				Map<String, Object> deliveryMap = JSONUtil.parseObj(deliveryJsonStr);
				if (!StringUtils.isEmpty(deliveryMap)) {
					String deliveryType = MapUtils.getString(deliveryMap, "deliveryType");
					if("1".equals(deliveryType)){
						fanhuaCar.setDeliveryType(deliveryType);
						fanhuaCar.setDeliveryName(MapUtils.getString(deliveryMap, "name"));
						fanhuaCar.setDeliveryPhone(MapUtils.getString(deliveryMap, "phone"));
						fanhuaCar.setDeliveryProvince(MapUtils.getString(deliveryMap, "province"));
						fanhuaCar.setDeliveryCity(MapUtils.getString(deliveryMap, "city"));
						fanhuaCar.setDeliveryArea(MapUtils.getString(deliveryMap, "area"));
						fanhuaCar.setDeliveryAddress(MapUtils.getString(deliveryMap, "address"));
						fanhuaCar.setDeliveryZip(MapUtils.getString(deliveryMap, "zip"));
						fanhuaCar.setDeliveryExpressNumber(MapUtils.getString(deliveryMap, "expressNumber"));
						fanhuaCar.setDeliveryExpressCompanyName(MapUtils.getString(deliveryMap, "expressCompanyName"));
						fanhuaCar.setDeliverySyElecPolicyFilePath(MapUtils.getString(deliveryMap, "syElecPolicyFilePath"));
						fanhuaCar.setDeliveryJpElecPolicyFilePath(MapUtils.getString(deliveryMap, "jpElecPolicyFilePath"));
					}else if("0".equals(deliveryType)){
						fanhuaCar.setDeliveryType(deliveryType);
						fanhuaCar.setDeliveryProvince(MapUtils.getString(deliveryMap, "province"));
						fanhuaCar.setDeliveryCity(MapUtils.getString(deliveryMap, "city"));
						fanhuaCar.setDeliveryArea(MapUtils.getString(deliveryMap, "area"));
						fanhuaCar.setDeliveryAddress(MapUtils.getString(deliveryMap, "address"));
						fanhuaCar.setDeliveryOutDept(MapUtils.getString(deliveryMap, "outDept"));
					}
				}
			} catch (Exception e) {
				Log4j2LogFactory.get().error("deliveryMap save error");
			}

			fanhuaCar.setModelStatus(ModelStatus.add);
			if (!applyChange(fanhuaCar)) {
				Log4j2LogFactory.get().error("fanhuaCarService applyChange error");
			}

			String riskKindsJsonStr = fanhuaCar.getRiskKinds();
			if (!StringUtils.isEmpty(riskKindsJsonStr)) {
				JSONArray jsonArr = JSONArray.parseArray(riskKindsJsonStr);
				String riskCode[] = new String[jsonArr.size()];
				String riskName[] = new String[jsonArr.size()];
				String amount[] = new String[jsonArr.size()];
				String notDeductible[] = new String[jsonArr.size()];
				String premium[] = new String[jsonArr.size()];
				String ncfPremium[] = new String[jsonArr.size()];

				for (int i = 0; i < jsonArr.size(); i++) {
					riskCode[i] = jsonArr.getJSONObject(i).getString("riskCode");
					riskName[i] = jsonArr.getJSONObject(i).getString("riskName");
					amount[i] = jsonArr.getJSONObject(i).getString("amount");
					notDeductible[i] = jsonArr.getJSONObject(i).getString("notDeductible");
					premium[i] = jsonArr.getJSONObject(i).getString("premium");
					ncfPremium[i] = jsonArr.getJSONObject(i).getString("ncfPremium");
				}
				for (int i = 0; i < riskCode.length; i++) {
					FanhuaCarBusinessRiskKinds fanhuaCarBusinessRiskKinds = new FanhuaCarBusinessRiskKinds();
					fanhuaCarBusinessRiskKinds.setId(CommonUtils.getKeyId());
					fanhuaCarBusinessRiskKinds.setCreateTime(DateUtils.getCurrent());
					fanhuaCarBusinessRiskKinds.setRiskCode(riskCode[i]);
					fanhuaCarBusinessRiskKinds.setRiskName(riskName[i]);
					fanhuaCarBusinessRiskKinds.setAmount(amount[i]);
					fanhuaCarBusinessRiskKinds.setNotDeductible(notDeductible[i]);
					fanhuaCarBusinessRiskKinds.setPremium(premium[i]);
					fanhuaCarBusinessRiskKinds.setNcfPremium(ncfPremium[i]);
					fanhuaCarBusinessRiskKinds.setOid(fanhuaCar.getId());
					fanhuaCarBusinessRiskKinds.setModelStatus(ModelStatus.add);

					if (!fanhuaCarBusinessRiskKindsService.applyChange(fanhuaCarBusinessRiskKinds)) {
						Log4j2LogFactory.get().error("fanhuaCarBusinessRiskKindsService applychange error");
					}
				}
			}
			// 核保成功/20
			if("20".equals(zzbDataCallback.getTaskState())){
				
				if(!tomeasureService.setTomeasure(fanhuaCar, zzbDataCallback)){
					throw new RuntimeException("tomeasure set error");
				}
				ArrayList<String> params = new ArrayList<String>();
				params.add(fanhuaCar.getApplicantName());
				params.add(zzbDataCallback.getTaskId());
				//18926423989
				String phone = "18926423989";
				Integer templId = SsmConfiguration.getInstance().getValueInt(SsmManageContainer.cesuanTemplId);
				System.err.println("templId*****"+templId);
				String ipAddress ="192.168.200.186";
				
				if(!sendMsgService.sendVerifyNoParams(phone, templId, ipAddress, params)){
					throw new RuntimeException("cesuan duanxin fasongshibai");
				}	
			}
			
			// 支付成功/25在进入我的保单
			if ("25".equals(zzbDataCallback.getTaskState())) {
				if(!listPolicyService.setFanhuaCarPolicy(fanhuaCar)){
					throw new RuntimeException("listPolicy set error");
				}
			}
			
			// 交易完成，即状态为承保成功/23时车险进入分润体系
			if ("23".equals(zzbDataCallback.getTaskState())) {
	
				ArrayList<String> params = new ArrayList<String>();
				params.add(fanhuaCar.getApplicantName());
				params.add(fanhuaCar.getCarLicenseNo());
				params.add(fanhuaCar.getBizInsureInfoPolicyNo());
				//18926423989
				String phone = "18926423989";
				Integer templId = SsmConfiguration.getInstance().getValueInt(SsmManageContainer.fenrunTemplId);
				System.err.println("templId*****"+templId);
				String ipAddress ="192.168.200.186";
				
				if(!sendMsgService.sendVerifyNoParams(phone, templId, ipAddress, params)){
					Log4j2LogFactory.get().error("cesuan duanxin fasongshibai");
				}	
				
				if(!carBrokerageRecordService.setCarBrokerageRecords(fanhuaCar)){
					throw new RuntimeException("carBrokerageRecord set error");
				}
				
			}
			
		}
		return "ok";
	}
}